<?php

/**
 *author: wangjinxi
 * 图片上传 
 */
namespace app\api\controller\v1;

use app\api\controller\BaseController;
use think\Response;

class Tools extends BaseController{
    
    public function upload(){
        $mid=$this->getLoginId();
//         if(empty($mid)){
//             return $this->returnResult(-7,'请登录!');
//         }
        $files = request()->file('image');
        if(is_array($files)){
            $urls = [];
            foreach($files as $file){
                $result= $this->_upload($file);
                list($url,$msg) = $result;
                if($url){
                    $urls [] = $url;
                }
            }
            return $this->returnResult(1,'上传成功',['urls'=>$urls]);
        }else{
            // 移动到框架应用根目录/public/uploads/ 目录下
            $file = $files;
            if($file){
                $result= $this->_upload($file);
                list($url,$msg) = $result;
                if($url){
                    return $this->returnResult(1,'上传成功',['url'=>$url]);
                }else{
                    // 上传失败获取错误信息
                    return $this->returnResult(0,$msg);
                }
            }
        }
        
        
        return $this->returnResult(-1,"参数错误");
    }
    
    private function _upload($file){
        $size =10485760;// 1024 * 1024 * 10; 10m
        $path =  'uploads';
        $info = $file->validate(['size'=>$size,'ext'=>'jpg,jpeg,png,gif'])->rule('md5')->move(ROOT_PATH . 'public' . DS .$path);
        if($info){
            $url = DS.$path.DS.$info->getSaveName();
            $url = str_replace("\\", "/", $url);
            return [$url,'成功'];
        }else{
            // 上传失败获取错误信息
//             return $this->returnResult(0,$file->getError());
            return [false,$file->getError()];
        }
    }
    
    public function qrcode(){
        $url = $this->request->param('url');
        $Response = new Response();
        $Response->header('Content-Type', 'image/png');
        $Response->contentType('Content-Type: image/png');
        $Response->content(qrcode($url,8));
        return $Response;
    }
}